import browser from "webextension-polyfill";
 
import { getDomCookies } from "../utils/common"
import { SD_SYSTEM } from "@src/globalData/enum";
import { getCookieValByKey } from "@src/utils/common";
import { saveMainSystemHeaders, saveSportMarketHeaders, saveStorageUserinfo } from "@src/entries/background/utils/common";

/** 现货交易系统的 headers */
export const getSpotMarketHeaders = ():RequestInit['headers'] => {
  const token = document.getElementsByTagName('iframe')?.[0]?.contentDocument?.getElementsByName('_csrf')?.[0]?.getAttribute('content') || ''
  const Cookie = getDomCookies()
  return {
    'X-Csrf-Token': token,
    Cookie
  }
}

/** 递归轮询 获取unitid的 */
const getUnitidLoop = (resolve:Function) => {
  const unitid =  document.getElementsByTagName('iframe')?.[0]?.contentDocument?.getElementById('unitSelect')?.children?.[0]?.getAttribute('value') || null
  if(unitid) return resolve(unitid)
  setTimeout(() => {
    getUnitidLoop(resolve)
  }, 1500)
}

/** 等待递归轮询 获取unitid的 Promise*/
const getUnitid = ():Promise<any> => {
  return new Promise((resolve, reject) => {
    window.addEventListener('beforeunload', () => {
      reject('listen getUnitid end')
    })
    getUnitidLoop(resolve)
  })
}

/** 回应 background 中监听的tab的Promise */
export const listenSendHeader = () => {
  browser.runtime.onMessage.addListener(async (params) => {
    
    /**
     * type 获取的数据类型
     * mark 当前执行此代码的页面
     */
    const {type, mark} = params
    
    switch(type) {
      // 现货市场 headers
      case 'GetHeaders':
        // 获取现货系统的headers
        if(mark === SD_SYSTEM.SPOT_MARKET) {
          return Promise.resolve(getSpotMarketHeaders())
        }
        // 获取主系统的headers
        if(mark === SD_SYSTEM.MAIN) {
          const Cookie = getDomCookies() as string
          const tag = getCookieValByKey(Cookie, 'ClientTag=')
          const tick = getCookieValByKey(Cookie, 'Admin-Token=')
          const xToken = getCookieValByKey(Cookie, 'X-Token=')
          const headers = {
            Cookie,'X-Ticket':tick, 'Clienttag':tag, 'X-Token':xToken,
            Accept: `application/json, text/plain, */*`,
            'Content-Type': `application/json;charset=UTF-8`,
            // Currentroute: `/pxf-settlement-extnet/statementConfirm-SD?billsType=D1`
          }
          saveMainSystemHeaders(headers)
          return Promise.resolve(headers)
        }
        break;
      case 'GetUserInfo':
        // 获取主系统中的 用户信息
        if(mark === SD_SYSTEM.MAIN) {
          let userInfo:any = window.sessionStorage.getItem('KUANGJIAZU-PXF-COMMON-PORTAL-SESSION-userInfo-')
          userInfo = userInfo && JSON.parse(userInfo)
          if(userInfo?.userName !== import.meta.env.VITE_APP_ACCOUNT) {
            saveStorageUserinfo('')
            const errTip = '实际账号与打包配置账号不一致'
            console.error(errTip)
            return Promise.reject(new Error(errTip))
          }
          saveStorageUserinfo(userInfo)
          return Promise.resolve(userInfo)
        }
        if(mark === SD_SYSTEM.SPOT_MARKET) {
          const unitid = await getUnitid()
          return Promise.resolve(unitid)
        }
        break;

        case 'GetZcqInfo': {
          if(mark === SD_SYSTEM.SPOT_MARKET_ZCQ) {
            return Promise.resolve(getSpotMarketHeaders())
          }
        }
        break;
      default:
        break;
    }
  });
}